package com.stillalive.springtrans.controller;

import com.stillalive.springtrans.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RequestMapping("/user1")
@RestController
public class UserController1 {
    @Autowired
    private UserService userService;

    @Autowired
    private TransactionDefinition definitions;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @RequestMapping("/register")
    public String registry(String name, String password){
        // 开启事务
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(definitions);
        // 用户注册
        userService.registerUser(name, password);
        // 事务提交
        dataSourceTransactionManager.commit(transactionStatus);
        dataSourceTransactionManager.rollback(transactionStatus);
        return "success";
    }
}
